package com.feature50.makeover.utils;

import org.apache.log4j.Logger;

import java.awt.*;
import java.io.InputStream;

public class FontResolver {
    private static Logger logger = Logger.getLogger(FontResolver.class);

    // fixme: change the default font behavior to integrate with the look-and-feel
    public static Font DEFAULT_FONT = new Font("Arial", Font.PLAIN, 10);

    public static Font getFont(FontInfo... font) {
        for (int i = 0; i < font.length; i++) {
            FontInfo fontInfo = font[i];

            if (fontInfo.isExternal()) {
                InputStream in = ResourceLoader.getInstance().getInputStream(
                        ResourceLoader.Type.Font,
                        "LucidaGrandeBold" + (fontInfo.isTruetype() ? ".ttf" : ".pfb")
                );
                try {
                    Font f = Font.createFont((fontInfo.isTruetype() ? Font.TRUETYPE_FONT : Font.TYPE1_FONT), in);
                    f = f.deriveFont(Font.PLAIN, (float) fontInfo.getSize());
                    return f;
                } catch (Exception e) {
                    logger.debug("Couldn't load font", e);
                }
            } else {
                Font f = new Font(fontInfo.getName(), Font.PLAIN, fontInfo.getSize());

                // "Dialog" is the default font name should a font not resolve
                if ((f.getFontName().equals("Dialog")) && (!fontInfo.getName().equals("Dialog"))) continue;

                return f;
            }

        }

        return DEFAULT_FONT;
    }

    public static class FontInfo {
        private String name;
        private boolean external = false;
        private boolean truetype = false;
        private int size;

        public FontInfo(String name, int size) {
            this.name = name;
            this.size = size;
        }

        public FontInfo(String name, int size, boolean external, boolean truetype) {
            this.truetype = truetype;
            this.external = external;
            this.name = name;
            this.size = size;
        }

        public String getName() {
            return name;
        }

        public int getSize() {
            return size;
        }

        public boolean isExternal() {
            return external;
        }

        public boolean isTruetype() {
            return truetype;
        }
    }
}
